package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;

import static org.springframework.amqp.rabbit.annotation.Exchange.TRUE;

/**
 * Package: com.atguigu.tingshu.order.receiver
 *
 * @author xiongkunYang
 * @description:
 * @since 2025/6/26 17:20
 */
@Slf4j
@Component
public class OrderReceiver {

    private final OrderInfoService orderInfoService;

    public OrderReceiver(OrderInfoService orderInfoService) {
        this.orderInfoService = orderInfoService;
    }

    /**
     * 监听取消订单消息
     *
     * @param orderId 订单id
     * @param message 消息
     * @param channel 信道
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(
                    value = MqConst.EXCHANGE_CANCEL_ORDER,
                    delayed = TRUE,
                    arguments = {@Argument(name = "x-delayed-type", value = "direct")}
            ),
            value = @Queue(value = MqConst.QUEUE_CANCEL_ORDER, durable = TRUE),
            key = MqConst.ROUTING_CANCEL_ORDER
    ))
    public void userRegister(Long orderId, Message message, Channel channel) {
        Assert.notNull(orderId, "订单id不能为空");
        log.info("[订单服务]监听取消订单消息，订单id：{}", orderId);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            this.orderInfoService.cancelOrder(orderId);
            channel.basicAck(deliveryTag, false);
            log.info("[订单服务]订单id：{}, 取消订单成功", orderId);
        } catch (IOException e) {
            log.error("[订单服务]订单id：{}, 取消订单失败", orderId);
            channel.basicNack(deliveryTag, false, true);
        }
    }
}